import { getStore } from '../store/index'
import { navigateTo } from '../crossplatform/apiservice/navigate'
import pagejumplist from '../configuration/pagejumplist.json'

// store
const store = getStore()
let {
  userinfo: {
    userId,
    userInfoC: { userName: userNameC },
    userInfoB: { userName: userNameB },
    role
  }
} = store.getState()

store.subscribe(handleUserInfoChange)
function handleUserInfoChange() {
  const {
    userinfo: {
      userId: newUserId,
      userInfoC: { userName: newUserNameC },
      userInfoB: { userName: newUserNameB },
      role: newRole
    }
  } = store.getState()
  if (
    userId !== newUserId ||
    userNameC !== newUserNameC ||
    userNameB !== newUserNameB ||
    role !== newRole
  ) {
    userId = newUserId
    userNameC = newUserNameC
    userNameB = newUserNameB
    role = newRole
  }
}

export const judgeLoginStatus = ({ url = '', parmas = '' }) => {
  if (role === 'personal') {
    // C端
    if (userNameC && url) {
      url &&
        navigateTo({
          url: `${pagejumplist[url + ''].path}${parmas ? `?${parmas}` : ''}`
        })
    } else {
      if (userId) {
        navigateTo({
          url: `${pagejumplist['base-information'].path}${parmas ? `?${parmas}` : ''}`
        })
      } else {
        navigateTo({
          url: `${pagejumplist['onekey-login'].path}${parmas ? `?${parmas}` : ''}`
        })
      }
    }
  } else {
    // B端
    if (userNameB && url) {
      url &&
        navigateTo({
          url: `${pagejumplist[url + ''].path}${parmas ? `?${parmas}` : ''}`
        })
    } else {
      if (userId) {
        navigateTo({
          url: `${pagejumplist['base-information'].path}${parmas ? `?${parmas}` : ''}`
        })
      } else {
        navigateTo({
          url: `${pagejumplist['onekey-login'].path}${parmas ? `?${parmas}` : ''}`
        })
      }
    }
  }
}
